import { Component , ViewChild } from '@angular/core';
import { Platform , Keyboard , IonicApp , Nav , ToastController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { HomePage } from '../pages/home/home';
import { WelcomePage } from '../pages/welcome/welcome';
import { Storage } from '@ionic/storage';
import { LoginPage } from '../pages/login/login';
import { BifrostProvider } from '../providers/bifrost/bifrost';
@Component({
  templateUrl: 'app.html'
})
export class MyApp {

  @ViewChild(Nav) nav : Nav;
  @ViewChild('page-login') login : LoginPage;

  private exit_switch : boolean = false;

  rootPage:any = WelcomePage;

  constructor(
    private platform: Platform, 
    statusBar: StatusBar, 
    splashScreen: SplashScreen , 
    private keyboard : Keyboard ,
    private ionicApp : IonicApp , 
    private toast : ToastController,
    private storage : Storage,
    private bifrost : BifrostProvider
  ) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();
      platform.registerBackButtonAction(()=>{
        this.exitApp();
      });
    });

    this.registerBackButton();

    this.bifrost.loginPass.subscribe(res=>{
      if(res){
        this.rootPage = HomePage;
      }
    });
    
    
    //延时三s欢迎页
    setTimeout(()=>{
      storage.get('isLogin').then((res)=>{
        if(res){
          this.rootPage = HomePage;
        }else{
          this.rootPage = LoginPage;
        }
      })
    },3000);

  }

  

  private registerBackButton(){
    this.platform.registerBackButtonAction(()=>{
      if(this.keyboard.isOpen()){
        this.keyboard.close();
        return;
      }
      let activePortal = this.ionicApp._modalPortal.getActive() || this.ionicApp._overlayPortal.getActive();
      let loadingPortal = this.ionicApp._loadingPortal.getActive();
      //modal处理
      //alert处理
      //actionsheet 处理
      if(activePortal){
        activePortal.dismiss().catch((err)=>{
          console.log(err);
        });
        return;
      }
      //loading处理
      if(loadingPortal){
        loadingPortal.dismiss().catch((err)=>{
          console.log(err);
        });
        return;
      }
      //如果页面可以返回 返回页面
      this.nav.canGoBack() ? this.nav.pop() : this.exitApp();
    },1);
  }

  //退出APP
  private exitApp(){
    if(this.exit_switch){
      this.platform.exitApp();
    }else{
      this.exit_switch = true;
      let toast = this.toast.create({
        message : '再按一次退出App',
        duration : 2000,
        position : 'top'
      });
      toast.present();
      setTimeout(()=>{this.exit_switch = false;},2000);
    }
  }   
}

